<?php


namespace app\index\model;


use app\index\common\Common;
use think\Exception;
use think\Model;

class PurchaseDetail extends Model
{
    public static $product_type=['1'=>'PC','2'=>'KG'];
    public $type_list=[['id'=>0,'label'=>'普通采购单'],['id'=>1,'label'=>'新品采购'],['id'=>2,'label'=>'找货单']];
    public $priority_list=['低','高'];
    public $purchase_status=['待采购','部分采购','已采购','无法采购'];
    public $ship_status=['未到货','已到货'];
    public $stock_status=['未入库','已入库','无法入库'];

    public static function getPurchasedParam(){
        $PurchaseDetailClass=new self();

        return ['purchase_status'=>$PurchaseDetailClass->purchase_status,'ship_status'=>$PurchaseDetailClass->ship_status,'stock_status'=>$PurchaseDetailClass->stock_status,'type_list'=>$PurchaseDetailClass->type_list,'priority_list'=>$PurchaseDetailClass->priority_list];
    }

    /**
     * getPurchasedList
     * 已建采购单列表
     * @url
     * @method
     * @param array $search_param
     * @param array $page_param
     * @return array
     * @throws \think\exception\DbException
     * @author Asira
     * @date 2021/3/11
     */
    public static function getPurchasedList($search_param, $page_param): array
    {
        $PurchaseDetailClass=new self();

        $where['pd.del_flag']=['=',0];
        $where['p.del_flag']=['=',0];

        if(is_numeric($search_param['stock_status'])){
            $where['pd.stock_status'] = ['=', $search_param['stock_status']];
        }
        if(is_numeric($search_param['ship_status'])){
            $where['pd.ship_status'] = ['=', $search_param['ship_status']];
        }
        if(is_numeric($search_param['purchase_status'])){
            $where['pd.status'] = ['=', $search_param['purchase_status']];
        }
        if(is_numeric($search_param['vendor'])){
            $where['pd.vendor_id'] = ['=', $search_param['vendor']];
        }
        if(!empty($search_param['create_time'])){
            $where['pd.create_time'] = ['between',[$search_param['create_time'].' 00:00:00',$search_param['create_time'].' 23:59:59']];
        }
        if(is_numeric($search_param['type'])){
            $where['p.type'] = ['=', $search_param['type']];
        }
        if(is_numeric($search_param['priority'])){
            $where['pd.priority'] = ['=', $search_param['priority']];
        }
        if (!empty($search_param['search_key']) && !empty($search_param['search_value'])) {
            if($search_param['search_key']==='purchase_id'){
                $purchase_id=explode(' ',$search_param['search_value']);
                $where['p.purchase_id'] = ['in', $purchase_id];
            }else {
                $where['pd.' . $search_param['search_key']] = ['like', '%'.$search_param['search_value'].'%'];
            }
        }

        $obj=$PurchaseDetailClass->alias('pd')
            ->join('purchase p','pd.pur_id=p.id','left')
            ->join('vendor v','pd.vendor_id=v.id','left')
            ->join('user u','pd.create_user=u.id','left')
            ->where($where)
            ->field('pd.id,p.purchase_id,pd.en_name,pd.cn_name,pd.type,pd.pur_id,pd.remark,pd.amount,pd.pur_price,pd.real_pur_amount,pd.real_pur_price,pd.waybill_no,pd.vendor_id,v.company vendor_name,pd.status,pd.ship_status,pd.stock_status,pd.image,pd.create_time,pd.last_update_time,pd.priority,p.type purchase_type,u.user_name')
            ->order('pur_id asc,status desc,priority desc')
            ->paginate($page_param['page_size'],false,['page'=>$page_param['page_num']]);
        if($obj->isEmpty()){
            return ['status'=>true,'result'=>['data'=>[],'total'=>0]];
        }
        $count=$obj->total();
        $data=$obj->items();
        foreach ($data as $key=>$value){
            $data[$key]['purchase_type_text']=$PurchaseDetailClass->type_list[$value['purchase_type']]['label'];
            $data[$key]['purchase_status_text']=$PurchaseDetailClass->purchase_status[$value['status']];
            $data[$key]['ship_status_text']=$PurchaseDetailClass->ship_status[$value['ship_status']];
            $data[$key]['stock_status_text']=$PurchaseDetailClass->stock_status[$value['stock_status']];
            $data[$key]['create_date']=explode(' ',$value['create_time'])[0];
            $data[$key]['image_thumb']=Common::getThumbImage($value['image']);
        }
        return ['status'=>true,'result'=>['data'=>$data,'total'=>$count]];
    }

    /**
     * purchaseUpdateStatus
     * 更新采购信息
     * @url
     * @method
     * @param int $id 采购单详情id
     * @param array $update 更新信息
     * @return array
     * @throws \think\exception\PDOException
     * @author Asira
     * @date 2021/3/11
     */
    public static function purchaseUpdateStatus($id, $update): array
    {
        $PurchaseDetailClass=new self();
        $ProductClass=new Product();
        $PurchaseDetailClass->startTrans();
        try {
            $old=$PurchaseDetailClass->where('id',$id)->where('status',0)->where('del_flag',0)->field('id,pur_id,amount,pro_id')->find();
            if(empty($old)){
                throw Exception('未找到符合条件的采购单');
            }
            $stock=$ProductClass->where('id',$old['pro_id'])->where('del_flag',0)->lock(true)->field('in_transit_stock,id')->find();

            if($old['amount']>$update['real_pur_amount']){
                $update['status']=1;
            }else{
                $update['status']=2;
            }
            $update['last_update_time']=date('Y-m-d H:i:s');
            $result=$PurchaseDetailClass->where('id', $id)->update($update);
            if($result===false){
                throw Exception('更新采购单失败');
            }

            if(!empty($stock)) {
                $stock['in_transit_stock'] = round($stock['in_transit_stock'] - $old['amount']+$update['real_pur_amount'], 2);

                $result = $ProductClass->where('id', $old['pro_id'])->update(['in_transit_stock' => $stock['in_transit_stock']]);
                if ($result === false) {
                    throw Exception('更新库存失败');
                }
            }

            $PurchaseDetailClass->commit();
            return ['status'=>true,'result'=>'更新成功'];
        }catch (Exception $e){
            $PurchaseDetailClass->rollback();
            trace('pur price error '.$e->getMessage(),'error');
            return ['status'=>false,'result'=>'更新失败. '.$e->getMessage()];
        }
    }

    public static function purchaseAddRemark($id,$remark){
        $PurchaseDetailClass=new self();
        $result=$PurchaseDetailClass->where('id', $id)->update(['remark'=>$remark]);
        if($result===false){
            return ['status'=>false,'result'=>'更新备注失败'];
        }
        return ['status'=>true,'result'=>'更新备注成功'];
    }

    /**
     * purchaseUpdateUnable
     * 无法采购
     * @url
     * @method
     * @param int $id 采购单详情id
     * @param string $remark 备注
     * @return array
     * @throws \think\exception\PDOException
     * @author Asira
     * @date 2021/3/11
     */
    public static function purchaseUpdateUnable($id, $remark): array
    {
        $PurchaseDetailClass=new self();
        $ProductClass=new Product();

        $PurchaseDetailClass->startTrans();
        try {
            $old=$PurchaseDetailClass->where('id',$id)->where('status','in',[0,1,2])->where('ship_status',0)->where('del_flag',0)->field('id,pur_id,amount,pro_id')->find();

            if(empty($old)){
                throw Exception('未找到符合条件的采购单');
            }
            $stock=$ProductClass->where('id',$old['pro_id'])->where('del_flag',0)->lock(true)->field('in_transit_stock,id')->find();
            $result=$PurchaseDetailClass->where('id', $id)->update(['status'=>3,'remark'=>$remark]);
            if($result===false){
                throw Exception('更新采购单失败');
            }
            if(!empty($stock)) {
                $stock['in_transit_stock'] = round($stock['in_transit_stock'] - $old['amount'], 2);

                $result = $ProductClass->where('id', $old['pro_id'])->update(['in_transit_stock' => $stock['in_transit_stock']]);
                if ($result === false) {
                    throw Exception('更新库存失败');
                }
            }
            $PurchaseDetailClass->commit();
            return ['status'=>true,'result'=>'更新成功'];
        }catch (Exception $e){
            $PurchaseDetailClass->rollback();
            trace('pur price error '.$e->getMessage(),'error');
            return ['status'=>false,'result'=>'更新失败. '.$e->getMessage()];
        }
    }

    /**
     * purchaseReceipt
     * 更新采购单到货
     * @url
     * @method
     * @param int $id 采购单详情id
     * @return array
     * @throws \think\exception\PDOException
     * @author Asira
     * @date 2021/3/11
     */
    public static function purchaseReceipt($id): array
    {
        $PurchaseDetailClass=new self();
        $PurchaseDetailClass->startTrans();
        try {
            $old=$PurchaseDetailClass->where('id',$id)->where('status','in',[1,2])->where('ship_status',0)->where('del_flag',0)->field('id,pur_id,amount')->find();
            if(empty($old)){
                throw Exception('未找到符合条件的采购单');
            }
            $result=$PurchaseDetailClass->where('id', $id)->update(['ship_status'=>1,'last_update_time'=>date('Y-m-d H:i:s')]);
            if($result===false){
                throw Exception('更新采购单失败');
            }
            $PurchaseDetailClass->commit();
            return ['status'=>true,'result'=>'更新成功'];
        }catch (Exception $e){
            $PurchaseDetailClass->rollback();
            trace('pur price error '.$e->getMessage(),'error');
            return ['status'=>false,'result'=>'更新失败. '.$e->getMessage()];
        }
    }

    public static function updateWaybillBatch($ids,$waybill_no){
        $PurchaseDetailClass=new self();
        $PurchaseDetailClass->startTrans();
        try {
            $old=$PurchaseDetailClass->where('id','in',$ids)->where('status','in',[1,2])->where('ship_status',0)->where('del_flag',0)->field('id,pur_id,amount')->select();
            if(empty($old)){
                throw Exception('未找到符合条件的采购单');
            }
            $update=[];
            $time=date('Y-m-d H:i:s');
            foreach ($old as $key=>$value){
                $update[]=['id'=>$value['id'],'waybill_no'=>$waybill_no,'last_update_time'=>$time];
            }
            $result=$PurchaseDetailClass->isUpdate()->saveAll($update);
            if($result===false){
                throw Exception('更新采购单运单号失败');
            }

            $PurchaseDetailClass->commit();
            return ['status'=>true,'result'=>'更新成功'];
        }catch (Exception $e){
            $PurchaseDetailClass->rollback();
            trace('pur price error '.$e->getMessage(),'error');
            return ['status'=>false,'result'=>'更新失败. '.$e->getMessage()];
        }
    }

    public static function getConfirmList($search_param,$page_param)
    {
        $PurchaseDetailClass=new self();
        $where['pd.del_flag']=['=',0];
        $where['pd.ship_status']=['=',1];
        $where['pd.stock_status']=['=',0];

        if (!empty($search_param['search_key']) && !empty($search_param['search_value'])) {
            if($search_param['search_key']==='purchase_id'){
                $purchase_id=explode(' ',$search_param['search_value']);
                $where['p.purchase_id'] = ['in', $purchase_id];
            }else {
                $where['pd.' . $search_param['search_key']] = ['like', '%'.$search_param['search_value'].'%'];
            }
        }

        $obj=$PurchaseDetailClass
            ->alias('pd')
            ->join('__PURCHASE__ p','pd.pur_id=p.id','left')
            ->join('__PRODUCT__ pro','pd.pro_id=pro.id','left')
            ->join('vendor v','v.id = pd.vendor_id','left')
            ->where($where)
            ->field('pd.id,pd.pur_id,pd.pro_id,pd.en_name,pd.waybill_no,pd.cn_name,pd.type,p.type pur_type,pd.real_pur_amount,p.purchase_id,pd.real_pur_price,pd.remark,pd.warehouse,IFNULL(pd.weight,pro.weight) weight,v.company vendor,pd.vendor_id company,IFNULL(pd.image,pro.image) image')
            ->paginate($page_param['page_size'],false,['page'=>$page_param['page_num']]);
        if($obj->isEmpty()){
            return ['status'=>true,'result'=>['data'=>[],'total'=>0]];
        }
        $count=$obj->total();
        $data=$obj->items();
        foreach ($data as $key=>$value){
            $data[$key]['thumb_image']=Common::getThumbImage($value['image']);
        }
        return ['status'=>true,'result'=>['data'=>$data,'total'=>$count]];
    }

    public static function stockIn($data,$id)
    {
        $PurchaseDetailClass=new PurchaseDetail();
        $PurchaseHistoryClass=new PurchaseHistory();
        $ProductClass = new Product();
        $ProductPurHistoryClass=new ProductPurHistory();
        $Purchase=new Purchase();
        $PurchaseDetailClass->startTrans();
        try {
            $old_product=$ProductClass->where('id',$data['pro_id'])->lock(true)->field('amount,weight,type,pur_price,in_transit_stock')->find();
            if(empty($old_product)){
                throw Exception('未找到符合条件的商品');
            }
            $purchase_detail=$PurchaseDetailClass->where('id',$id)->lock(true)->where('ship_status',1)->where('stock_status',0)->where('del_flag',0)->field('real_pur_amount,pur_id')->find();
            if(empty($purchase_detail)){
                throw Exception('未找到符合条件的采购单');
            }
            $purchase=$Purchase->where('id',$purchase_detail['pur_id'])->where('del_flag',0)->field('type')->find();
            $pur_price=round(($data['pur_price']*$data['amount']+$old_product['pur_price']*$old_product['amount'])/($data['amount']+$old_product['amount']),2);

            $update_product=[
                'amount'=>round($data['amount']+$old_product['amount'],4),
                'pur_price'=>$pur_price,
                'vendor_id'=>$data['vendor_id'],
                'selling_price'=>$data['selling_price'],
                'in_transit_stock'=>$old_product['in_transit_stock']-$purchase_detail['real_pur_amount'],
                'image'=>$data['image'],
            ];
            if($purchase['type']===1){
                unset($update_product['in_transit_stock']);
            }

            $result=$ProductClass->where('id',$data['pro_id'])->update($update_product);
            if($result===false){
                throw Exception('更新商品库存失败');
            }
            $result=$PurchaseDetailClass->where('id',$id)->update(['image'=>$data['image'],'stock_status'=>1]);
            if($result===false){
                throw Exception('更新采购单失败');
            }
            $result=$ProductPurHistoryClass->insert(['pro_id'=>$data['pro_id'],'pur_detail_id'=>$id,'pur_price'=>$data['pur_price'],'amount'=>$data['amount'],'create_user'=>$data['create_user'],'type'=>1,'vendor_id'=>$data['vendor_id']]);
            if($result===false){
                return ['status'=>false,'result'=>'保存入库历史失败'];
            }
            $result=$PurchaseHistoryClass->insert(['pur_detail_id'=>$id,'operational'=>'采购单入库','operator'=>$data['create_user']]);
            if($result===false){
                return ['status'=>false,'result'=>'保存采购历史失败'];
            }
            $PurchaseDetailClass->commit();
            return ['status'=>true,'result'=>['msg'=>'入库成功','pro_id'=>$data['pro_id']]];
        }catch (Exception $e) {
            $PurchaseDetailClass->rollback();
            trace('purchase stock in'.$e->getMessage(),'error');
            return ['status'=>false,'result'=>'入库失败'.$e->getMessage()];
        }
    }

    public static function createProduct($data,$id)
    {
        $PurchaseDetailClass=new PurchaseDetail();
        $PurchaseHistoryClass=new PurchaseHistory();
        $ProductClass = new Product();
        $ProductPurHistoryClass=new ProductPurHistory();

        $repeat=$ProductClass->where(function ($query)use($data){
            $query->where('cn_name','=',$data['cn_name'])->whereOr('en_name','=',$data['en_name']);
        })->where('del_flag',0)->where('warehouse',$data['warehouse'])->field('id,cn_name,en_name')->find();
        if(!empty($repeat)){
            return ['status'=>false,'result'=>'商品名已被使用 '.' '.$repeat['cn_name'].' '.$repeat['en_name']];
        }
        $purchase_detail=$PurchaseDetailClass->where('id',$id)->lock(true)->where('ship_status',1)->where('stock_status',0)->where('del_flag',0)->field('real_pur_amount,pur_id')->find();
        if(empty($purchase_detail)){
            throw Exception('未找到符合条件的采购单');
        }
        $PurchaseDetailClass->startTrans();
        try{
            $ProductClass->data($data);
            $result=$ProductClass->save();
            if($result===false){
                return ['status'=>false,'result'=>'添加失败'];
            }
            $pro_id=$ProductClass->id;
            $ProductPurHistoryClass->data(['pro_id'=>$pro_id,'pur_detail_id'=>$id,'pur_price'=>$data['pur_price'],'type'=>1,'amount'=>$data['amount'],'create_user'=>$data['create_user'],'vendor_id'=>$data['vendor_id']]);
            $result=$ProductPurHistoryClass->save();
            if($result===false){
                return ['status'=>false,'result'=>'保存入库历史失败'];
            }

            $result=$PurchaseDetailClass->where(['id'=>$id])->update(['stock_status'=>1]);
            if($result===false){
                return ['status'=>false,'result'=>'保存采购单失败'];
            }
            $result=$PurchaseHistoryClass->insert(['pur_detail_id'=>$id,'operational'=>'采购单入库','operator'=>$data['create_user']]);
            if($result===false){
                return ['status'=>false,'result'=>'保存采购历史失败'];
            }

            $PurchaseDetailClass->commit();
            return ['status'=>true,'result'=>['msg'=>'创建成功','pro_id'=>$pro_id]];
        }catch (Exception $e){
            $PurchaseDetailClass->rollback();
            trace('purchase create product'.$e->getMessage(),'error');
            return ['status'=>false,'result'=>'创建失败'.$e->getMessage()];
        }
    }

    public static function stockInById($id){
        $PurchaseDetailClass=new PurchaseDetail();
        $PurchaseHistoryClass=new PurchaseHistory();
        $ProductClass = new Product();
        $ProductPurHistoryClass=new ProductPurHistory();

        $PurchaseDetailClass->startTrans();
        try {
            $purchase=$PurchaseDetailClass->where('id',$id)->lock(true)->where('ship_status',1)->where('stock_status',0)->where('del_flag',0)->field('pro_id,real_pur_price,real_pur_amount')->find();
            if(empty($purchase)){
                throw Exception('未找到符合条件的采购单');
            }

            $old_product=$ProductClass->where('id',$purchase['pro_id'])->where('del_flag',0)->lock(true)->field('amount,weight,type,pur_price,in_transit_stock,vendor_id')->find();
            if(empty($old_product)){
                throw Exception('未找到符合条件的商品');
            }

            $pur_price=round(($purchase['real_pur_price']*$purchase['real_pur_amount']+$old_product['pur_price']*$old_product['amount'])/($purchase['real_pur_amount']+$old_product['amount']),2);

            $update_product=[
                'amount'=>round($purchase['real_pur_amount']+$old_product['amount'],4),
                'pur_price'=>$pur_price,
                'in_transit_stock'=>$old_product['in_transit_stock']-$purchase['real_pur_amount'],
            ];

            $result=$ProductClass->where('id',$purchase['pro_id'])->update($update_product);
            if($result===false){
                throw Exception('更新商品库存失败');
            }
            $result=$PurchaseDetailClass->where('id',$id)->update(['stock_status'=>1]);
            if($result===false){
                throw Exception('更新采购单失败');
            }
            $result=$ProductPurHistoryClass->insert(['pro_id'=>$purchase['pro_id'],'pur_detail_id'=>$id,'pur_price'=>$purchase['real_pur_price'],'amount'=>$purchase['real_pur_amount'],'create_user'=>session('Login_user')['id'],'type'=>1,'vendor_id'=>$old_product['vendor_id']]);
            if($result===false){
                return ['status'=>false,'result'=>'保存入库历史失败'];
            }
            $result=$PurchaseHistoryClass->insert(['pur_detail_id'=>$id,'operational'=>'采购单入库','operator'=>session('Login_user')['id']]);
            if($result===false){
                return ['status'=>false,'result'=>'保存采购历史失败'];
            }
            $PurchaseDetailClass->commit();
            return ['status'=>true,'result'=>['msg'=>'入库成功','pro_id'=>$purchase['pro_id']]];
        }catch (Exception $e) {
            $PurchaseDetailClass->rollback();
            trace('purchase stock in'.$e->getMessage(),'error');
            return ['status'=>false,'result'=>'入库失败'.$e->getMessage()];
        }
    }

    public static function endPurchase($id){
        $PurchaseDetailClass=new PurchaseDetail();
        $PurchaseHistoryClass=new PurchaseHistory();
        $ProductClass = new Product();

        $PurchaseDetailClass->startTrans();
        try {
            $purchase = $PurchaseDetailClass->where('id', $id)->lock(true)->where('ship_status', 1)->where('stock_status',0)->where('del_flag', 0)->field('pro_id,real_pur_amount')->find();
            if (empty($purchase)) {
                throw Exception('未找到符合条件的采购单');
            }
            if($purchase['pro_id']) {
                $old_product = $ProductClass->where('id', $purchase['pro_id'])->where('del_flag', 0)->lock(true)->field('amount,weight,type,pur_price,in_transit_stock')->find();
                if (empty($old_product)) {
                    throw Exception('未找到符合条件的商品');
                }
                $update_product = [
                    'in_transit_stock' => $old_product['in_transit_stock'] - $purchase['real_pur_amount'],
                ];
                $result = $ProductClass->where('id', $purchase['pro_id'])->update($update_product);
                if ($result === false) {
                    throw Exception('更新商品库存失败');
                }
            }
            $result=$PurchaseDetailClass->where('id',$id)->update(['stock_status'=>2]);
            if($result===false){
                throw Exception('更新采购单失败');
            }
            $result=$PurchaseHistoryClass->insert(['pur_detail_id'=>$id,'operational'=>'采购单完结','operator'=>session('Login_user')['id']]);
            if($result===false){
                return ['status'=>false,'result'=>'保存采购历史失败'];
            }
            $PurchaseDetailClass->commit();
            return ['status'=>true,'result'=>'完结成功'];
        }catch(Exception $e){
            $PurchaseDetailClass->rollback();
            trace('purchase end'.$e->getMessage(),'error');
            return ['status'=>false,'result'=>'完结失败'.$e->getMessage()];
        }
    }

    /**
     * 通过ids获取同一供应商下的采购详情列表
     * create by yhb on 2021/4/2 16:59
     * @param array $purchaseDetailIds
     * @param array $vendorId
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getPurchaseDetailByIds($purchaseDetailIds= [],$vendorId = [])
    {
        if(count(array_unique($vendorId)) > 1){
            if(count($vendorId) === count(array_unique($vendorId))){
                return ['status'=>false,'result'=>'请确保它们是同一个供应商'];
            }
        }

        $data = $this->where('pd.id','in',$purchaseDetailIds)
            ->alias('pd')
            ->where('pd.del_flag',0)
            ->field('pd.id,pd.pro_id,pd.vendor_id, pd.cn_name,pd.amount,pd.pur_price,pd.remark,pd.type')
            ->select()
            ->toArray();

        if(empty($data)){
            return ['status'=>false,'result'=>'未找到采购商品'];
        }

        return ['status'=>true,'result'=>['data'=>$data]];
    }

    /**
     *  执行批量修改运单
     * create by yhb on 2021/4/2 17:00
     * @param $data
     * @return array|\think\response\Json
     * @throws \Exception
     */
    public function updatePurchaseDetail($data)
    {
        $PurchaseDetailClass = new self();
        $ids=[];
        $pro_ids=[];
        $insert_purchase_detail=[];
        if(!empty($data)){
            foreach ($data['purchase_detail'] as $k=>$v){
                $insert_purchase_detail[$v['id']] = [
                    'waybill_no' => $data['waybill_no'],
                    'real_pur_amount' => $v['amount'],
                    'real_pur_price' => $v['pur_price'],
                    'remark' => $v['remark']??'',
                    'status' => 2,
                    'vendor_id'=>$data['vendor'],
                    'id'=>$v['id']
                ];
                $ids[]=$v['id'];
                if(isset($v['pro_id']) && $v['pro_id']) {
                    $pro_ids[] = $v['pro_id'];
                }
            }
        }else{
            return json(['status'=>false,'msg'=>'请填写需要采购商品']);
        }
        $PurchaseDetailClass->startTrans();
        try {
            if (!empty($pro_ids)) {
                $ProductClass = new Product();
                $purchase_data = $PurchaseDetailClass->where('id', 'in', $ids)->where('status',0)->field('id,pro_id,amount')->select()->toArray();
                $product_data=$ProductClass->where('id', 'in', $pro_ids)->field('id,in_transit_stock')->select()->toArray();
                $product_data_list=[];
                foreach ($product_data as $key=>$value){
                    $product_data_list[$value['id']]=$value;
                }
                foreach ($purchase_data as $key => $value) {
                    if ($value['pro_id']) {
                        $arr=&$product_data_list[$value['pro_id']];
                        $real_pur_amount = $insert_purchase_detail[$value['id']]['real_pur_amount'];
                        $arr['in_transit_stock']=$arr['in_transit_stock']-$value['amount']+$real_pur_amount;
                    }
                }

                if(!empty($product_data_list)){
                    $result=$ProductClass->isUpdate(true)->saveAll($product_data_list);
                    if($result===false) {
                        return ['status' => false, 'result' => '更新商品失败'];
                    }
                }
            }
            $result = $PurchaseDetailClass->isUpdate(true)->saveAll($insert_purchase_detail);
            if($result===false) {
                return ['status' => false, 'result' => '添加采购失败'];
            }
            $PurchaseDetailClass->commit();
            return ['status'=>true,'result'=>'添加成功'];
        }catch (Exception $e){
            $PurchaseDetailClass->rollback();
            trace('updatePurchaseDetail '.$e->getMessage(),'error');
            return ['status'=>false,'result'=>'添加采购失败'];
        }

    }

    /**
     * 批量到货
     * create by yhb on 2021/4/6 15:45
     * @param $id
     * @return array
     * @throws \think\exception\PDOException
     */
    public function updateBatchDelivery($id)
    {
        $PurchaseDetailClass=new self();

        $PurchaseDetailClass->startTrans();
        try {
            $old=$PurchaseDetailClass->where('id','in',$id)->where('status','in',[1,2])->where('ship_status',0)->where('del_flag',0)->field('id,pur_id,amount')->select();
            if(count($old) < count($id)){
               return ['status'=>false,'result'=>'未找到符合条件的采购单'];
            }
            $result=$PurchaseDetailClass->where('id','in', $id)->update(['ship_status'=>1,'last_update_time'=>date('Y-m-d H:i:s')]);
            if($result===false){
                throw Exception('更新批量采购单失败');
            }
            $PurchaseDetailClass->commit();
            return ['status'=>true,'result'=>'批量更新成功'];
        }catch (Exception $e){
            $PurchaseDetailClass->rollback();
            trace('pur price error '.$e->getMessage(),'error');
            return ['status'=>false,'result'=>'批量更新失败. '.$e->getMessage()];
        }
    }
}